package it.infodea.tapestrydea.components;

import it.infodea.tapestrydea.support.DeaUtils;

import java.io.IOException;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.runtime.Component;

/**
 * Used to display the template and class sources of the container page.
 * 
 * @author rob
 * 
 */
@IncludeStylesheet(value = "../assets/styles/tapestrydea.css")
public class ShowSourceDea {
	private static final String EXT_TML = ".tml";

	private static final String EXT_JAVA = ".java";

	/**
	 * Determines if the template source is initially visible. By default true.
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	@Property(write = false)
	private boolean showTml = true;

	/**
	 * Determines if the class source is initially visible. By default false.
	 */
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	@Property(write = false)
	private boolean showJava = false;

	@Inject
	private ComponentResources resources;

	private String path;

	private String name;

	@BeginRender
	void setup() {
		Class<? extends Component> containerPageClass = resources.getContainer().getClass();
		path = containerPageClass.getName().replace('.', '/');
		name = containerPageClass.getSimpleName();
	}

	private String getCode(String ext) {
		try {
			return DeaUtils.fileToString(path + ext);
		} catch (IOException e) {
		}
		return "";
	}

	public String getTmlName() {
		return name + EXT_TML;
	}

	public String getJavaName() {
		return name + EXT_JAVA;
	}

	public String getTmlCode() {
		return getCode(EXT_TML);
	}

	public String getJavaCode() {
		return getCode(EXT_JAVA);
	}

	public String getTmlStyle() {
		return showTml ? "" : "display: none;";
	}

	public String getJavaStyle() {
		return showJava ? "" : "display: none;";
	}

}
